package com.nintendo.gateway.filters;

import com.alibaba.nacos.shaded.com.google.gson.Gson;
import com.nintendo.gateway.properties.ExcludeProperties;
import com.nintendo.result.GraceJSONResult;
import com.nintendo.result.ResponseStatusEnum;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.util.MimeTypeUtils;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.nio.charset.StandardCharsets;
import java.util.List;

import static com.nintendo.base.BaseInfoProperties.USER_TOKEN_PREFIX;

@Component
public class AuthGlobalFilter implements GlobalFilter, Ordered {
    @Autowired
    private RedisTemplate<String, Object> redisTemplate;
    @Autowired
    private ExcludeProperties excludeProperties;
    @Autowired
    private AntPathMatcher antPathMatcher;
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        String path = exchange.getRequest().getPath().toString();
        if(isExcludePath(path)){
            return chain.filter(exchange);
        }
        String userToken = exchange.getRequest().getHeaders().getFirst("userToken");
        System.out.println("前端传递的userToken==>"+userToken);
        String userId = exchange.getRequest().getHeaders().getFirst("userId");
        Object userTokenObj = redisTemplate.opsForValue().get(USER_TOKEN_PREFIX + userId);
        System.out.println("redis中存的userToken==>"+userTokenObj);
        System.out.println("前端传递的userId=====>"+userId);
        if(userToken==null){
            return GatewayErrorResponse(exchange,ResponseStatusEnum.USER_NOT_LOGIN);
        }
        if(!userToken.equals(userTokenObj)){
            return GatewayErrorResponse(exchange,ResponseStatusEnum.USER_TOKEN_ERROR);
        }
        return chain.filter( exchange);
    }

    private boolean isExcludePath(String path) {
        List<String> excludePaths = excludeProperties.getExcludePaths();
        for (String excludePath : excludePaths) {
            if(antPathMatcher.match(excludePath,path)){
                return true;
            }
        }
        return false;
    }

    private Mono<Void> GatewayErrorResponse(ServerWebExchange exchange ,ResponseStatusEnum responseStatus) {
        ServerHttpResponse response = exchange.getResponse();
        GraceJSONResult jsonResult =GraceJSONResult.exception(responseStatus);
        // 3. 设置header类型
        if (!response.getHeaders().containsKey("Content-Type")) {
            response.getHeaders().add("Content-Type",
                    MimeTypeUtils.APPLICATION_JSON_VALUE);
        }

        // 4. 修改response的状态码code为500
        response.setStatusCode(HttpStatus.INTERNAL_SERVER_ERROR);

        // 5. 转换json并且像response中写入数据
        String resultJson = new Gson().toJson(jsonResult);
        DataBuffer buffer = response
                .bufferFactory()
                .wrap(resultJson.getBytes(StandardCharsets.UTF_8));
        return response.writeWith(Mono.just(buffer));
    }


    @Override
    public int getOrder() {
        return 0;
    }
}
